package com.itmk.system.home.service.Impl;

import com.itmk.config.redis.RedisUtils;
import com.itmk.constants.Constant;
import com.itmk.system.common.service.RedisService;
import com.itmk.system.home.service.HomeService;
import com.itmk.system.home.vo.HomeRespVO;
import com.itmk.system.home.vo.MakeMenuTree;
import com.itmk.system.home.vo.MenuVo;
import com.itmk.system.home.vo.UserInfoRespVO;
import com.itmk.system.permission.entity.Permission;
import com.itmk.system.permission.service.PermissionService;
import com.itmk.system.user.mapper.SysUserMapper;
import com.itmk.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
@Slf4j
public class HomeServiceImpl implements HomeService {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisService redisService;
    @Override
    public HomeRespVO getHomeRespVo(Long userId) {
        HomeRespVO homeRespVO=new HomeRespVO();
        String redisKey= Constant.HOME_REDIS_KEY +"_"+userId.toString();
//        先从缓存里找如果有返回
        if(redisService.hasKey(redisKey)){
            homeRespVO= RedisUtils.RedisToObject(redisService.get(redisKey).toString(),HomeRespVO.class);
        }else{
            MenuVo menuVo=new MenuVo();
//        根据userid获取权限集合
            List<Permission> permissionList=permissionService.getPermissionListByUserId(userId);
//        找出所有权限类型为2 的权限集合  也就是按钮类型
            List<Permission> permissions = permissionList.stream().filter(item -> item != null && !item.getType().equals("2")).collect(Collectors.toList());
//        生成菜单目录树
            List<Permission> listMenu = MakeMenuTree.makeTree(permissions, 0L);
//找出所有权限类型为1 的权限集合 也就是路由
            List<Permission> routerList = permissionList.stream().filter(item -> item != null && item.getType().equals("1")).collect(Collectors.toList());
            menuVo.setRouterList(routerList);
            menuVo.setMenuList(listMenu);

//            SysUser user=userService.findSimpleUserInfoById(userId);
            UserInfoRespVO userInfoRespVO=this.sysUserMapper.getUserInfoByUserId(userId);
            homeRespVO.setMenus(menuVo);
            homeRespVO.setUserInfoVO(userInfoRespVO);
            redisService.set(redisKey,homeRespVO,5, TimeUnit.MINUTES);
        }
        return homeRespVO;
    }
}
